package com.nian.search.es.service.impl;

import com.nian.search.es.dao.ItemRepository;
import com.nian.search.es.model.Item;
import com.nian.search.es.service.IItemService;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 用途：
 * 开发：zhangmj
 * 日期：2020/4/11 0011 17:29
 */
@Service
public class ItemServiceImpl implements IItemService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private ItemRepository itemRepository;

    @Override
    public void addIndexTest() {
        elasticsearchRestTemplate.createIndex(Item.class);
        elasticsearchRestTemplate.putMapping(Item.class);
    }

    @Override
    public void deleteIndex() {
        elasticsearchRestTemplate.deleteIndex("item");
    }

    @Override
    public Item add(Item model) {
        return itemRepository.save(model);
    }

    @Override
    public Item update(Long id, Item model) {
        return itemRepository.save(model);
    }

    @Override
    public Item save(Item model) {
        return itemRepository.save(model);
    }

    @Override
    public Iterable<Item> saveAll(List<Item> list) {
        return itemRepository.saveAll(list);
    }

    @Override
    public Item getById(Long id) {
        if(id != null){
            Optional<Item> itemOptional = itemRepository.findById(id.toString());
            return itemOptional.orElse(null);
        }
        return null;
    }

    @Override
    public Page<Item> findByTileCategoryBrand(String title, String category, String brand) {
        title = title.toLowerCase();
        category = category.toLowerCase();
        brand = brand.toLowerCase();
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        MatchQueryBuilder titleQ = QueryBuilders.matchQuery("title", title);
        MatchQueryBuilder categoryQ = QueryBuilders.matchQuery("category", category);
        MatchQueryBuilder brandQ = QueryBuilders.matchQuery("brand", brand);
        nativeSearchQueryBuilder.withQuery(titleQ).withQuery(categoryQ).withQuery(brandQ);
        return elasticsearchRestTemplate.queryForPage(nativeSearchQueryBuilder.build(), Item.class);
    }

    @Override
    public Iterable<Item> findByTile(String title) {
        MatchQueryBuilder titleQ = QueryBuilders.matchQuery("title", title);
        return itemRepository.search(titleQ);
    }

    @Override
    public Page<Item> search(String query) {
        return findByTileCategoryBrand(query, query, query);
    }
}
